package cn.team11.sds.dayi;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.multidex.MultiDexApplication;
import android.util.Log;

import com.alibaba.sdk.android.openaccount.Environment;
import com.alibaba.wireless.security.open.SecurityGuardManager;
import com.alibaba.wireless.security.open.staticdatastore.IStaticDataStoreComponent;
import com.aliyun.alink.AlinkSDK;
import com.aliyun.alink.alirn.RNGlobalConfig;
import com.aliyun.alink.alirn.rnpackage.biz.BizPackageHolder;
import com.aliyun.alink.bone.CdnEnv;
import com.aliyun.alink.business.account.OALoginBusiness;
import com.aliyun.alink.business.alink.ALinkEnv;
import com.aliyun.alink.business.helper.ChannelBindHelper;
import com.aliyun.alink.business.login.IAlinkLoginCallback;
import com.aliyun.alink.sdk.jsbridge.BonePluginRegistry;
import com.aliyun.alink.utils.ALog;
import com.facebook.react.FrescoPackage;
import com.imnjh.imagepicker.PickerConfig;
import com.imnjh.imagepicker.SImagePicker;
import com.taobao.accs.ACCSManager;
import com.taobao.accs.IAppReceiver;
import com.taobao.accs.client.AccsConfig;
import com.taobao.accs.common.Constants;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;

import org.android.spdy.SpdyProtocol;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import cn.team11.sds.dayi.envconfig.EnvConfigure;
import cn.team11.sds.dayi.qrcode.QRCodeHelper;
import cn.team11.sdsPackager.T11EyesPlugin;
import cn.team11.sdsPackager.T11ImagePickerPlugin;
import cn.team11.sdsPackager.T11MsgChannelPlugin;
import cn.team11.sdsPackager.T11ScanQrcodePlugin;
import cn.team11.sdsPackager.T11ShellVersionPlugin;
import cn.team11.smarteye.activity.InComingActiviity;
import cn.team11.smarteye.activity.callback.CateyeActivityCallback;
import cn.team11.smarteye.bean.CateyeEvent;
import cn.team11.smarteye.bean.DaoMaster;
import cn.team11.smarteye.bean.DaoSession;
import cn.team11.smarteye.misc.SConstants;
import cn.team11.smarteye.service.CatEyeService;
import cn.team11.util.T11Log;
import cn.team11.util.imagePicker.FrescoImageLoader;
import mtopsdk.mtop.intf.MtopSetting;

/**
 * Created by huanyu.zhy on 16/12/7.
 */
public class SampleApplication extends MultiDexApplication {

    private static final String TAG = "SampleApplication";
    private ALinkEnv alinkEnv = ALinkEnv.Online;
    private CdnEnv cdnEnv = CdnEnv.Release;
    private String appkey;
    private static SampleApplication instance;

    private DaoMaster.DevOpenHelper mHelper;
    private SQLiteDatabase db;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;
    public static SampleApplication instances;

    public static Context getAppContext() {
        return instance;
    }

    public void showVersion(){
        PackageManager pm = this.getPackageManager();
        try {
            PackageInfo pi = pm.getPackageInfo(this.getPackageName(), 0);
            T11Log.d("versionCode = "+pi.versionCode+",  versionName = "+pi.versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onCreate() {
        super.onCreate();

        showVersion();

        instance = this;
        initEnv();

        getAppKey();
        initAlinkSDK();
        initAccs();

        QRCodeHelper.init(this);

        SImagePicker.init(new PickerConfig.Builder().setAppContext(this)
                .setImageLoader(new FrescoImageLoader())
                .setToolbaseColor((R.color.colorPrimary))
                .build());

        initCateyeService();
    }

    private void initEnv() {
        EnvConfigure.init(this);
        if (EnvConfigure.aLinkEnv != null) {
            alinkEnv = EnvConfigure.aLinkEnv;
        } else {
            EnvConfigure.saveAlinkEnv(this, alinkEnv);
        }

        if (EnvConfigure.cdnEnv != null) {
            cdnEnv = EnvConfigure.cdnEnv;
        } else {
            EnvConfigure.saveCDNEnv(this, cdnEnv);
        }
    }

    private void getAppKey() {
        try {
            int index;
            if (alinkEnv == ALinkEnv.Daily) {
                index = 2;
            } else {
                index = 0;
            }

            SecurityGuardManager sgMgr = SecurityGuardManager.getInstance(this);
            if (sgMgr != null) {
                IStaticDataStoreComponent sdsComp = sgMgr.getStaticDataStoreComp();
                if (sdsComp != null) {
                    appkey = sdsComp.getAppKeyByIndex(index, "");
                    T11Log.d("安全图片中读取到的appKey = " + appkey);
                }
            }
        } catch (Exception e) {
            ALog.e(TAG, "", e);
        }
    }

    // init ACCS
    private void initAccs() {

        int env = Constants.DEBUG;
        if (alinkEnv == ALinkEnv.Preview) {
            env = Constants.PREVIEW;
        } else if (alinkEnv == ALinkEnv.Online) {
            env = Constants.RELEASE;
        }

        AccsConfig.setSecurityGuardOff(AccsConfig.SECURITY_TYPE.SECURITY_OPEN);
        AccsConfig.setGroup(AccsConfig.ACCS_GROUP.OPEN);
        AccsConfig.setAccsCenterHosts("openacs.m.taobao.com",
                "openacs.m.taobao.com", "openacs.m.taobao.com");
        AccsConfig.setChannelHosts("openjmacs.m.taobao.com",
                "openjmacs.m.taobao.com", "openjmacs.m.taobao.com");
        AccsConfig.setAccsCenterIps(new String[]{"140.205.160.76"},
                new String[]{"140.205.172.12"},
                new String[]{"10.125.50.231"});
        AccsConfig.setChannelIps(new String[]{"140.205.163.94"},
                new String[]{"140.205.172.12"},
                new String[]{"10.125.50.231"});
        AccsConfig.setTnetPubkey(SpdyProtocol.PUBKEY_SEQ_OPEN, SpdyProtocol.PUBKEY_SEQ_OPEN);
        AccsConfig.setChannelReuse(false);

        com.taobao.accs.utl.ALog.setUseTlog(false);
        anet.channel.util.ALog.setUseTlog(false);
        ACCSManager.setMode(this, env);
        T11Log.e("start bind app");
        ACCSManager.bindApp(this, appkey, "ttidzorotest",
                new IAppReceiver() {
                    private final Map<String, String> SERVICES = new HashMap<String, String>() {

                        {
                            put("accs", "com.taobao.taobao.CallbackService");
                            put("accs-console", "com.taobao.taobao.CallbackService");
                            put("agooSend", "org.android.agoo.accs.AgooService");
                            put("agooAck", "org.android.agoo.accs.AgooService");
                            put("agooTokenReport", "org.android.agoo.accs.AgooService");
                        }
                    };

                    String TAG = "AppReceiver";

                    @Override
                    public void onData(String userId, String dataId, byte[] data) {
                        Log.d(TAG, "onData()");
                    }

                    @Override
                    public void onBindApp(int errorCode) {
                        Log.d(TAG, "onBindApp(): " + errorCode);
                        ChannelBindHelper.getInstance().registerChannel(
                                com.ut.device.UTDevice.getUtdid(SampleApplication.this),
                                "AGOO",
                                errorCode == 200);
                    }

                    @Override
                    public void onUnbindApp(int errorCode) {
                        Log.d(TAG, "onUnbindApp(): " + errorCode);
                    }

                    @Override
                    public void onBindUser(String userId, int errorCode) {
                        Log.d(TAG, "onBindUser(): " + userId + "/" + errorCode);
                    }

                    @Override
                    public void onUnbindUser(int errorCode) {
                        Log.d(TAG, "onUnbindUser(): " + errorCode);
                    }

                    @Override
                    public void onSendData(String dataId, int errorCode) {
                        Log.d(TAG, "onSendData(): " + errorCode);
                    }

                    @Override
                    public String getService(String serviceId) {
                        String service = SERVICES.get(serviceId);
                        return service;
                    }

                    @Override
                    public Map<String, String> getAllServices() {
                        return SERVICES;
                    }
                });
        T11Log.e("end bind app");
    }

    private void initAlinkSDK() {
        AlinkSDK.setLogLevel(ALog.LEVEL_DEBUG);

        // init account & open sdk
        {

            OALoginBusiness oaBiz = new OALoginBusiness();

            IAlinkLoginCallback alinkLoginCallback = new IAlinkLoginCallback() {
                @Override
                public void onSuccess() {
//                    Toast.makeText(SampleApplication.this, "账号初始化成功,启动bone页面", Toast.LENGTH_SHORT).show();
                    ALog.d(TAG, "账号初始化成功，启动bone页面");
                }

                @Override
                public void onFailure(int code, String message) {
//                    Toast.makeText(SampleApplication.this, "账号初始化异常: " + message, Toast.LENGTH_LONG).show();
                    ALog.d(TAG, "账号初始化异常：" + message);
                }
            };

            Environment env = Environment.TEST;
            if (alinkEnv == ALinkEnv.Preview) {
                env = Environment.PRE;
            } else if (alinkEnv == ALinkEnv.Online) {
                env = Environment.ONLINE;
            } else if (alinkEnv == ALinkEnv.Sandbox) {
                env = Environment.SANDBOX;
            }
            oaBiz.init(getApplicationContext(), env, alinkLoginCallback);

            MtopSetting.setAppKeyIndex(0, 2);
            AlinkSDK.setEnv(this, alinkEnv);
            AlinkSDK.init(SampleApplication.this, appkey, oaBiz);
        }

        // add image support with fresco
        BizPackageHolder bizPackageHolder = RNGlobalConfig.getBizPackageHolder();
        bizPackageHolder.addPackage(new FrescoPackage());

        // init boneKit if you need
        {
            AlinkSDK.setCdnEnv(cdnEnv);
            String appVersion = getAppVersion(this);
            AlinkSDK.initBoneKit(this, appkey, appVersion, true);
            BonePluginRegistry.register(T11ScanQrcodePlugin.API_NAME, T11ScanQrcodePlugin.class);
            BonePluginRegistry.register(T11ImagePickerPlugin.API_NAME,T11ImagePickerPlugin.class);
            BonePluginRegistry.register(T11ShellVersionPlugin.API_NAME,T11ShellVersionPlugin.class);
            //注册bone插件
            BonePluginRegistry.register(T11EyesPlugin.API_NAME,T11EyesPlugin.class);
            BonePluginRegistry.register(T11MsgChannelPlugin.API_NAME,T11MsgChannelPlugin.class);
        }
    }

    static String getAppVersion(Context context) {
        String version = "";

        try {

            String packageName = context.getPackageName();

            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);

            version = packageInfo.versionName;

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return version;
    }

    private void initCateyeService(){

        //初始化QR库
        ZXingLibrary.initDisplayOpinion(this);

        registerActivityLifecycleCallbacks(new CateyeActivityCallback());

        instances = this;
        //初始化消息记录数据库
        mHelper = new DaoMaster.DevOpenHelper(this, SConstants.TEAM_DB, null);
        db = mHelper.getWritableDatabase();
        mDaoMaster = new DaoMaster(db);
        mDaoSession = mDaoMaster.newSession();

        Intent intent = new Intent(getApplicationContext(), CatEyeService.class);
        startService(intent);

    }



    @Override
    public void onTerminate() {
        super.onTerminate();
        //关闭猫眼sdk服务
        CatEyeService.icvssUserModule.closeIcvss();
        stopService(new Intent(this, CatEyeService.class));
    }

    public DaoSession getDaoSession() {
        return mDaoSession;
    }
    public SQLiteDatabase getDb() {
        return db;
    }

    public static SampleApplication getInstances(){
        return instances;
    }


}
